package pm.core;

import pm.config.Configuration;
import pm.devices.drives.Drive;
import pm.devices.DevicesModule;
import pm.devices.DevicesModuleListener;
import pm.gui.GuiModule;
import pm.gui.GuiModuleListener;
import pm.oo.OOModule;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.math.BigDecimal;

/**
 * @author Anton Bernatski
 */
public class Core implements GuiModuleListener, DevicesModuleListener {

    protected Configuration configuration;
    protected GuiModule guiModule;
    protected OOModule ooModule;
    protected DevicesModule devicesModule;

    protected BigDecimal balans;
    private static final String PAGES = "pages";

    public Configuration getConfiguration() {
        return configuration;
    }

    public void openFile(final File file) {
        try {
            guiModule.showPrintScreen();
            ooModule.loadDocument(file, guiModule.getNativeOOViewComponent());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void closeCurrentDocument() {
        ooModule.closeCurrentDocument();
    }

    public void nextPage() {
        ooModule.nextPage();
    }

    public void previousPage() {
        ooModule.prevPage();
    }

    public void printDocument() {
        //todo 1. show print dialog
        //todo 2. call this.print();
    }

    public void print(Map params) {
        //todo call this.print();
    }

    public void preview() {
        File file = devicesModule.scanToFile();
        openFile(file);
        //todo open scanned in CopyPreviewScreen
    }

    public void scan() {
        File file = devicesModule.scanToFile();
        openFile(file);
        //todo open scanned in ScanPreviewScreen
    }

    public void save() {
        //todo 1. show file save dialog
        //todo 2. copy opened in ScanPreviewScreen file to user's removable disk
        BigDecimal scannedPrice = getConfiguration().getScanPrice();
        balans = balans.subtract(scannedPrice);
        guiModule.updateMoneyState(balans);
    }

    public void finish() {
        devicesModule.ejectChange(balans);
        balans = new BigDecimal(0);
        guiModule.updateMoneyState(balans);
    }

    public void drivesChanged(Drive[] updatedDrives) {
        guiModule.setDrives(updatedDrives);
    }

    public void moneyInserted(BigDecimal insertedMoney) {
        balans = balans.add(insertedMoney);
        guiModule.updateMoneyState(balans);
    }

    protected void printInternal(final Map printParams) {
        ooModule.print(printParams);
        Integer papersPrinted = (Integer)printParams.get(PAGES);
        BigDecimal printedPrice = getConfiguration().getPrintPrice().multiply(new BigDecimal(papersPrinted));
        balans = balans.subtract(printedPrice);
        guiModule.updateMoneyState(balans);
    }
}
